package org.rxc.auth.interceptor;

import org.rxc.auth.context.LoginContext;
import org.rxc.auth.mapper.RolePermissionMapper;
import org.rxc.base.annotation.PlatformAnnotation;
import org.rxc.org.domain.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头TOKEN
        String token = request.getHeader("TOKEN");
        //2.token为空
        if (token==null){
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            //{"success":false,"msg":"noLogin"}
            writer.print("{\"success\":false,\"msg\":\"noLogin\"}");
            return false;
        }
        //3.token不能再map里获取对象
        Employee employee = LoginContext.context.get(token);
        if (employee==null){
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.print("{\"success\":false,\"msg\":\"noLogin\"}");
            return false;
        }
        //4.验证当前的登录用户访问的功能是否有权限
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        PlatformAnnotation annotation = method.getAnnotation(PlatformAnnotation.class);
        if (annotation!=null){
            //当前用户拥有的权限
            List<String> permissionSn = rolePermissionMapper.getPermissionSnByEmpId(employee.getId());
            String methodName = method.getName();
            Class<?> beanType = handlerMethod.getBeanType();
            String simpleName = beanType.getSimpleName();
            if (permissionSn.contains(simpleName+":"+methodName)){
                return true;
            }else {
                response.setContentType("application/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.print("{\"success\":false,\"msg\":\"noPermission\"}");
                return false;
            }
        }
        return true;
    }
}
